# -*- coding: utf-8 -*-
# ****************************************************
# Author: yizuoliang
# Create: 2024/6/24
# Last Modified: 2024/6/24
# Last Editor:
# Description: 统一个返回格式
# ***************************************************
from functools import wraps

from flask import jsonify

from applications.common.app_exception import AppException
from applications.common.constants.status_codes import ResponseCode


def api_response(status_code, message, data=None):
    """构造统一的API响应格式"""
    return jsonify({
        'code': status_code,
        'message': message,
        'data': data
    })


# 统一返回格式的装饰器,切面编程
def response_wrapper(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            return api_response(ResponseCode.SUCCESS.code, ResponseCode.SUCCESS.message, result)
        except AppException as e:
            return api_response(e.code, e.message)

    return wrapper
